﻿using System;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using MediaPortal.Dialogs;
using MediaPortal.Player;
using MediaPortal.Configuration;
using BierdopjeTV;
using System.IO;
using BierdopjeTV.Configuration;
using System.Collections.Generic;

using SQLite.NET;

using System.Diagnostics;


//namespace BierdopjeTv
namespace BierdopjeTV
{

    [PluginIcons("BierdopjeTV.Bierdopje.gif", "BierdopjeTV.BierdopjeDisabled.gif")]
    public class BierdopjeTV : GUIWindow, ISetupForm
    {

        private int Selected_ShowID_Facade = 0;
        private int Selected_Season_Facade = 0;
        private int Selected_EpisodeID_Facade = 0;

        List<Database.GUISeries> _Shows;
        List<Database.GUISeasons> _Seasons;
        List<Database.GUIEpisodes> _Episodes;
        
        
        //Gui Stuff
        private string billboard_image = "";
        private string titel_serie = "";
  
        
        public string THUMBS_FOLDER =  Config.GetFile(Config.Dir.Thumbs, "BierdopjeTV");


        [SkinControlAttribute(8)]
        protected GUILabelControl m_ShowTitel = null;

        
        [SkinControlAttribute(99999)]
        protected GUILabelControl m_UpdateInfo = null;
        
        [SkinControlAttribute(9)]
        protected GUILabelControl m_Gekeken_Episodes = null;

        [SkinControlAttribute(10)]
        protected GUILabelControl m_Aantal_Episodes = null;

        [SkinControlAttribute(11)]
        protected GUILabelControl m_Vorige_Aflevering = null;

        [SkinControlAttribute(12)]
        protected GUILabelControl m_Volgende_Aflevering = null;

        [SkinControlAttribute(14)]
        protected GUILabelControl m_Duratie = null;

        [SkinControlAttribute(15)]
        protected GUILabelControl m_ShowStatus = null;

        [SkinControlAttribute(16)]
        protected GUILabelControl m_votes = null;


        [SkinControlAttribute(50)]
        protected GUIFacadeControl m_Facade = null;
 
        [SkinControlAttribute(1000)]        
        protected GUIImage m_BillBoard = null;

        [SkinControlAttribute(1001)]
        protected GUIImage m_SubsNL = null;

        [SkinControlAttribute(1002)]
        protected GUIImage m_SubsEN = null;
        [SkinControlAttribute(400)]
        protected GUITextScrollUpControl m_ShowSummary = null;

        [SkinControlAttribute(900)]
        protected GUIImageList m_Score = null;

        private VideoHandler m_VideoHandler;
        private int currentSelection;


        public BierdopjeTV()
        {
         
        }

        #region ISetupForm Members

        // Returns the name of the plugin which is shown in the plugin menu
        public string PluginName()
        {
            return "BierdopjeTV";
        }

        // Returns the description of the plugin is shown in the plugin menu
        public string Description()
        {
            return "Bierdopje TV Series";
        }

        // Returns the author of the plugin which is shown in the plugin menu
        public string Author()
        {
            return "Leroy Z.";
        }

        // show the setup dialog
        public void ShowPlugin()
        {
            Configuration.Configuration dialog = new Configuration.Configuration();
            dialog.ShowDialog();
        }

        // Indicates whether plugin can be enabled/disabled
        public bool CanEnable()
        {
            return true;
        }

        // Get Windows-ID
        public int GetWindowId()
        {
            // WindowID of windowplugin belonging to this setup
            // enter your own unique code
            return 7413;
        }

        // Indicates if plugin is enabled by default;
        public bool DefaultEnabled()
        {
            return true;
        }

        // indicates if a plugin has it's own setup screen
        public bool HasSetup()
        {
            return true;
        }

        public bool GetHome(out string strButtonText, out string strButtonImage,out string strButtonImageFocus, out string strPictureImage)
        {
            strButtonText = PluginName();
            strButtonImage = String.Empty;
            strButtonImageFocus = String.Empty;
            strPictureImage = String.Empty;
            return true;
        }

        // With GetID it will be an window-plugin / otherwise a process-plugin
        // Enter the id number here again
        public override int GetID
        {
            get { return 7413; }
            set {}
        }

        #endregion

        public override bool Init()
        {
            
            Helpers.Logger.WriteSimpel("Init()");
            Helpers.Logger.Write("Bierdopje TV Gestart", "Init()");

            if (Properties.Settings.Default.APIKEY.Length == 0)
            {
                Helpers.Logger.Write("GEEN API KEY INGEVULD!!!!", "Init()");

            }

            m_VideoHandler = new VideoHandler();
            currentSelection = 0;

            if (!Directory.Exists(THUMBS_FOLDER))
            {
                Directory.CreateDirectory(THUMBS_FOLDER);
            }

            return Load(GUIGraphicsContext.Skin + @"\BierdopjeTV.xml");
            
        }

        protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType)
        {
            //Helpers.Logger.Write(control.ToString() + " -> " + actionType.ToString(), "OnClicked()");
            
            //if (actionType != MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM) return;
            if (control == m_Facade && actionType == MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM) //enter / click
            {
                Helpers.Logger.WriteSimpel(actionType.ToString());
				if (currentSelection == 0) //if shows was entered
				{
                    Selected_ShowID_Facade = m_Facade.SelectedListItemIndex;
                    
				}
                if (currentSelection == 1) //if season was entered
                {
                    //Selected_Season_Facade = m_Facade[m_Facade.SelectedListItemIndex].ItemId;
                    Selected_Season_Facade = m_Facade.SelectedListItemIndex;
                    Helpers.Logger.WriteSimpel("selectedSeason is now : " + Selected_Season_Facade.ToString());
                }

                if (currentSelection == 2) //if episode was entered
                {
                    Selected_EpisodeID_Facade = m_Facade.SelectedListItemIndex;
                    Helpers.Logger.WriteSimpel("Selected_Episode is now : " + Selected_EpisodeID_Facade.ToString());
                } 
                
                currentSelection++;


                
                if (currentSelection > 2)
                {
                    currentSelection = 3;
                }
			      
                decideListView();

            }
                    
            base.OnClicked(controlId, control, actionType);
        }

        public override void OnAction(MediaPortal.GUI.Library.Action action)
        {
            //Helpers.Logger.Write(action.wID.ToString(), "OnAction()");
            
            
            //Escappe is nu ingedrukt.
            if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU)
            {
                 
                currentSelection--;
            
                if (currentSelection == -1)
                {
                    //let do mediaportal it's action
                    base.OnAction(action);
                }
                else
                {                   
                    decideListView();
                    return;
                }
            }
            if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_CONTEXT_MENU)
            {
                OnContextMenu();
            }
            base.OnAction(action);
        }

        public override bool OnMessage(GUIMessage message)
        {
            //Helpers.Logger.WriteSimpel("OnMessage() : " + message.Message.ToString());
            if (message.Message == GUIMessage.MessageType.GUI_MSG_ITEM_FOCUS_CHANGED)
            {
                if (message.SenderControlId == (int)m_Facade.GetID)
                {
                    //Selection on facade has changed, do some stuff												
                    if (currentSelection == 0) //Alleen bij Series doen!
                    {
                        Series_OnItemSelected(m_Facade.SelectedListItemIndex);
                    }
                    if (currentSelection == 1) //alleen bij Seasons doen!
                    {
                        Season_OnItemSelected(m_Facade.SelectedListItemIndex);
                    }
                    if (currentSelection == 2) //alleen bij Seasons doen!
                    {
                        Series_OnItemSelected(Selected_ShowID_Facade);
                        Episode_OnItemSelected(m_Facade.SelectedListItemIndex);
                    }
                  
                }
                //Helpers.Logger.WriteSimpel("OnMessage : currentselection = now: :" + currentSelection.ToString());
            }
            return base.OnMessage(message);
        }

        private void decideListView()
        {
            Helpers.Logger.WriteSimpel("decideListView()");

            switch (currentSelection)
            {
                case 0:
                    {
                        LoadSeries();
                        break;
                    }
                case 1:
                    {
                        LoadSeasons(_Shows[Selected_ShowID_Facade].ShowID);
                        break;
                    }
                case 2:
                    {                               
                        LoadEpisodes(_Shows[Selected_ShowID_Facade].ShowID, _Seasons[Selected_Season_Facade].Season);                    
                        break;
                    }
                case 3:
			        {
                        PlayEpisode();
                 
    				    break;
				    }
            }
        }

        private void GeefMelding(string header, string tekst)
        {
            GUIDialogOK dlg = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
            dlg.SetHeading(header);
            dlg.SetLine(1, tekst);
            dlg.SetLine(2, String.Empty);            
            dlg.DoModal(GUIWindowManager.ActiveWindow);

        }

        private void OnContextMenu()
        {
            Helpers.Logger.WriteSimpel("deciding currentselection: " + currentSelection.ToString());
            switch (currentSelection)
            {
                case 0: //series
                    ContextMenu_Series();
                    break;
                case 1: //season
                    ContextMenu_Seasons();
                    break;
                case 2: //episode
                    ContextMenu_Episodes();
                    break;
            }
        }

        private void ContextMenu_Series()
        {
            int aantalSubsNL = 0;
            int aantalSubsEN = 0;
            int selectieWas = 0;
            selectieWas = m_Facade.SelectedListItemIndex;

            API.APIFunctions _API = new API.APIFunctions();

            Helpers.Logger.WriteSimpel("OnContextMenu()");
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            dlg.Reset();
            dlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString());
            dlg.Add("Markeer alles als gezien");
            dlg.Add("Markeer niets als gezien");
            dlg.Add("Download ondertitels");
            dlg.Add("Forceer update vanaf bierdopje");
            dlg.Add("Forceer update van bestanden");
            //dlg.Add("Dit is de 4e optie");

            dlg.DoModal(GUIWindowManager.ActiveWindow);

            switch (dlg.SelectedLabelText)
            {
                case "Markeer alles als gezien":
                    Database.DBEpisodes.MarkAllWatched(_Shows[m_Facade.SelectedListItemIndex].ShowID, 0, 0);                    
                    break;
                case "Markeer niets als gezien":
                    Database.DBEpisodes.MarkAllUNWatched(_Shows[m_Facade.SelectedListItemIndex].ShowID, 0, 0);
                    break;
                case "Download ondertitels":
                    if (Database.Database.getSettingValue("UserKey").Length == 0)
                    {
                        GeefMelding("Fout:", "Je hebt je User key nog niet ingevuld!");
                    }
                    else
                    {

                        GUIDialogMenu subDlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
                        subDlg.Reset();
                        subDlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString() + " - Ondertitel taal: ");
                        subDlg.Add("Nederlandse Ondertitels");
                        subDlg.Add("Engelse Ondertitels");
                        subDlg.Add("Beide");
                        subDlg.DoModal(GUIWindowManager.ActiveWindow);
                        switch (subDlg.SelectedLabelText)
                        {
                            case "Nederlandse Ondertitels":
                                aantalSubsNL = Database.DBSubs.getShowSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "nl");
                                GeefMelding("Subs:", aantalSubsNL.ToString() + " Nederlandse Subs Gedownload");
                                break;
                            case "Engelse Ondertitels":
                                aantalSubsEN = Database.DBSubs.getShowSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "en");
                                GeefMelding("Subs:", aantalSubsEN.ToString() + " Engelse Subs Gedownload");
                                break;
                            case "Beide":
                                aantalSubsNL = Database.DBSubs.getShowSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "nl");
                                aantalSubsEN = Database.DBSubs.getShowSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "en");
                                GeefMelding("Subs:", aantalSubsEN.ToString() + " Engelse Subs Gedownload,\n" + aantalSubsNL.ToString() + " Nederlandse Subs Gedownload");
                                break;
                            case "Download ondertitels":
                                break;
                        }
                    }
                    break;

                case "Forceer update vanaf bierdopje":
                    m_UpdateInfo.Label = "Bezig met bijwerkeren vanaf bierdopje.com...";
                    API.BierdopjeShows.updateShow(_Shows[m_Facade.SelectedListItemIndex].ShowID);                        
                    API.BierdopjeEpisodes.UpdateEpisodes(_Shows[m_Facade.SelectedListItemIndex].ShowID, 0);
                    m_UpdateInfo.Label = "";
                    break;
                case "Forceer update van bestanden":
                    Database.DBEpisodes.removeLocalEpisodes();
                    //ForceLocalScan();
                    updateLocalSeries();
                    break;

            }
            if (dlg.SelectedLabelText != "")
            {
                Helpers.Logger.WriteSimpel("Lijst opnieuw opvragen....");
                LoadSeries();
                m_Facade.SelectedListItemIndex = selectieWas;
                
            }

        }

        private void ContextMenu_Seasons()
        {
            int aantalSubsNL = 0;
            int aantalSubsEN = 0;

            int selectieWas = 0;
            selectieWas = m_Facade.SelectedListItemIndex;

            API.APIFunctions _API = new API.APIFunctions();

            Helpers.Logger.WriteSimpel("OnContextMenu()");
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            dlg.Reset();
            dlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString());
            dlg.Add("Markeer als gezien");
            dlg.Add("Markeer als niet gezien");
            dlg.Add("Download ondertitels");

            dlg.DoModal(GUIWindowManager.ActiveWindow);

            switch (dlg.SelectedLabelText)
            {
                case "Markeer als gezien":
                    Database.DBEpisodes.MarkAllWatched(_Shows[Selected_ShowID_Facade].ShowID, _Seasons[m_Facade.SelectedListItemIndex].Season, 0);
                    break;
                case "Markeer als niet gezien":
                    Database.DBEpisodes.MarkAllUNWatched(_Shows[Selected_ShowID_Facade].ShowID, _Seasons[m_Facade.SelectedListItemIndex].Season, 0);
                    break;
                case "Download ondertitels":
                    if (Database.Database.getSettingValue("UserKey").Length == 0)
                    {
                        GeefMelding("Fout:", "Je hebt je User key nog niet ingevuld!");
                    }
                    else
                    {

                        GUIDialogMenu subDlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
                        subDlg.Reset();
                        subDlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString() + " - Ondertitel taal: ");
                        subDlg.Add("Nederlandse Ondertitels");
                        subDlg.Add("Engelse Ondertitels");
                        subDlg.Add("Beide");
                        subDlg.DoModal(GUIWindowManager.ActiveWindow);
                        switch (subDlg.SelectedLabelText)
                        {
                            case "Nederlandse Ondertitels":
                                aantalSubsNL = Database.DBSubs.getSeasonSubs(_Shows[Selected_ShowID_Facade].ShowID, m_Facade[m_Facade.SelectedListItemIndex].ItemId, "nl");
                                GeefMelding("Subs:", aantalSubsNL.ToString() + " Nederlandse Subs Gedownload");
                                break;
                            case "Engelse Ondertitels":
                                aantalSubsEN = Database.DBSubs.getSeasonSubs(_Shows[Selected_ShowID_Facade].ShowID, m_Facade[m_Facade.SelectedListItemIndex].ItemId, "en");
                                GeefMelding("Subs:", aantalSubsEN.ToString() + " Engelse Subs Gedownload");
                                break;
                            case "Beide":
                                aantalSubsNL = Database.DBSubs.getSeasonSubs(_Shows[Selected_ShowID_Facade].ShowID, m_Facade[m_Facade.SelectedListItemIndex].ItemId, "nl");
                                aantalSubsEN = Database.DBSubs.getSeasonSubs(_Shows[Selected_ShowID_Facade].ShowID, m_Facade[m_Facade.SelectedListItemIndex].ItemId, "en");
                                GeefMelding("Subs:", aantalSubsEN.ToString() + " Engelse Subs Gedownload,\n" + aantalSubsNL.ToString() + " Nederlandse Subs Gedownload");
                                break;
                            case "Download ondertitels":
                                break;
                        }
                    }
                    break;
            }
            if (dlg.SelectedLabelText != "")
            {
                Helpers.Logger.WriteSimpel("Lijst opnieuw opvragen....");
                LoadSeasons(_Shows[Selected_ShowID_Facade].ShowID);
                m_Facade.SelectedListItemIndex = selectieWas;
            }

        }

        private void ContextMenu_Episodes()
        {
            
            API.APIFunctions _API = new API.APIFunctions();
            int selectieWas = 0;
            selectieWas = m_Facade.SelectedListItemIndex;

            Helpers.Logger.WriteSimpel("OnContextMenu()");
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            dlg.Reset();
            dlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString());
            dlg.Add("Markeer als gezien");
            dlg.Add("Markeer als niet gezien");
            dlg.Add("Download ondertitels");
            //dlg.Add("Dit is de 4e optie");

            dlg.DoModal(GUIWindowManager.ActiveWindow);
            int aantalSubsNL = 0;
            int aantalSubsEN = 0;

            switch (dlg.SelectedLabelText)
            {
                case "Markeer als gezien":
                    Database.DBEpisodes.MarkAllWatched(0, 0, _Episodes[m_Facade.SelectedListItemIndex].EpisodeID);
                    break;
                case "Markeer als niet gezien":
                    Database.DBEpisodes.MarkAllUNWatched(0, 0, _Episodes[m_Facade.SelectedListItemIndex].EpisodeID);
                    break;
                case "Download ondertitels":
                    if (Database.Database.getSettingValue("UserKey").Length == 0)
                    {
                        GeefMelding("Fout:", "Je hebt je User key nog niet ingevuld!");
                    }
                    else
                    {

                        GUIDialogMenu subDlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
                        subDlg.Reset();
                        subDlg.SetHeading(m_Facade[m_Facade.SelectedListItemIndex].Label.ToString() + " - Ondertitel taal: ");
                        subDlg.Add("Nederlandse Ondertitels");
                        subDlg.Add("Engelse Ondertitels");
                        subDlg.Add("Beide");
                        subDlg.DoModal(GUIWindowManager.ActiveWindow);
                        switch (subDlg.SelectedLabelText)
                        {
                            case "Nederlandse Ondertitels":
                                aantalSubsNL = Database.DBSubs.getEpisodeSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "nl");
                                GeefMelding("Subs:", aantalSubsNL.ToString() + " Nederlandse Subs Gedownload");
                                break;
                            case "Engelse Ondertitels":
                                aantalSubsEN = Database.DBSubs.getEpisodeSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "en");
                                GeefMelding("Subs:", aantalSubsEN.ToString() + " Engelse Subs Gedownload");
                                break;
                            case "Beide":
                                aantalSubsNL = Database.DBSubs.getEpisodeSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "nl");                                
                                aantalSubsEN = Database.DBSubs.getEpisodeSubs(m_Facade[m_Facade.SelectedListItemIndex].ItemId, "en");
                                GeefMelding("Subs:", aantalSubsEN.ToString() + " Engelse Subs Gedownload,\n" + aantalSubsNL.ToString() + " Nederlandse Subs Gedownload");
                                break;
                            case "Download ondertitels":
                                break;
                        }
                    }
                    break;


            }
            if (dlg.SelectedLabelText != "")
            {
                Helpers.Logger.WriteSimpel("Lijst opnieuw opvragen....");
                LoadEpisodes(_Shows[Selected_ShowID_Facade].ShowID, _Seasons[Selected_Season_Facade].Season);
                m_Facade.SelectedListItemIndex = selectieWas;
            }

        }

        void ForceLocalScan()
        {
            ////Import.FileScanner _FileScanner = new Import.FileScanner();

            //_ImportFolders = Database.Database.GetImportPaths();



            //for (int i = 0; i < _ImportFolders.Count; i++)
            //{
            //    .Debug._ImportEpisodes = _FileScanner.getLocalShows(_ImportFolders[i]);
            //    //for (int j = 0; j < _ImportEpisodes.Count; j++)
            //    //{

            //    //    //if (_ImportEpisodes[j].ShowName != null)
            //    //    //{
            //    //    //    Helpers.Logger.WriteSimpel(_ImportEpisodes[j].ShowName);

            //    //    //}
            //    //}
            //}
                    
     
            //Helpers.Logger.WriteSimpel("");




        }


        protected override void OnPageLoad()
        {
            m_UpdateInfo.Label = "";
            Helpers.Logger.WriteSimpel("OnPageLoad()");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET Downloaded = 0");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET Downloaded = 1 WHERE EpisodeID IN (SELECT * FROM LocalEpisodeIDs)");
            //Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET SubNLDownloaded = 0");
            //Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET SubENDownloaded = 0");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET SubNLDownloaded = 1 WHERE EpisodeID IN (SELECT DISTINCT EpisodeID FROM LocalSubsID WHERE SubNL > 0)");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET SubENDownloaded = 1 WHERE EpisodeID IN (SELECT DISTINCT EpisodeID FROM LocalSubsID WHERE SubEN > 0)");
            


            if (m_VideoHandler.isPlaying) {
                currentSelection = 2;
                Series_OnItemSelected(Selected_ShowID_Facade);
            }
            if (currentSelection == -1)
            {
                currentSelection = 0;
            }
            Helpers.Logger.WriteSimpel("OnPageLoad() currentSelection -> " + currentSelection.ToString());

            //decideListView();            

            LoadFacade();            

        }


        void LoadFacade()
        {
            Helpers.Logger.WriteSimpel("LoadFacade()");
            m_Facade.View = GUIFacadeControl.ViewMode.List;
                        
            decideListView();

        }

        void LoadSeries()
        {
            Helpers.Logger.WriteSimpel("LoadSeries()");
            _Shows = Database.DBShows.getShows();

			this.m_Facade.Clear();

			GUIListItem item;

			for (int i = 0; i < _Shows.Count; i++)
			{
				item = new GUIListItem();
				item.ItemId = _Shows[i].ShowID;
                
				item.Label = _Shows[i].ShowName;
				item.Label2 = _Shows[i].Wachted.ToString() + "/" + _Shows[i].Downloaded.ToString();
                
                //Condities om te bepalen welke kleur iets krijgt :-)
                if (_Shows[i].Wachted >= _Shows[i].Downloaded)
                {
                    item.IsPlayed = true; //alle episodes zijn gezien                    
                }
                if (_Shows[i].Wachted == 0) //0 items gezien
                {
                    if (_Shows[i].Downloaded == 0) //geen episodes lokaal, en niets gezien.
                    {
                        item.IsRemote = true;                        
                    }
                }
				m_Facade.Add(item);
                
				item = null;
			}
            //selecteer wat de user geselect had :-)

            try
            {
                m_Facade.SelectedListItemIndex = Selected_ShowID_Facade;
            }
            catch (Exception Ex)
            {
                Helpers.Logger.WriteSimpel("\t\tLoadSeries() " + Ex.Message);
            }
            GUIControl.FocusControl(m_Facade.GetID, m_Facade.ListView.GetID);
    
        }

        void LoadSeasons(int ShowID)
        {
            Helpers.Logger.WriteSimpel("LoadSeasons()");

            int firstUnwatched = -1;
            
            _Seasons = Database.DBSeasons.getSeasons(ShowID);

            this.m_Facade.Clear();

            GUIListItem item;

            for (int i = 0; i < _Seasons.Count; i++)
            {
                item = new GUIListItem();
                Helpers.Logger.WriteSimpel("LoadSeasons() Season " + _Seasons[i].Season.ToString());
                item.ItemId = _Seasons[i].Season;
                item.Label = "Season " + _Seasons[i].Season.ToString() + " (" + _Seasons[i].Episodes.ToString() + " Episodes)";
                item.Label2 = _Seasons[i].Watched.ToString() + "/" + _Seasons[i].Downloaded.ToString();

                //Condities om te bepalen welke kleur iets krijgt :-)
                if (_Seasons[i].Watched >= _Seasons[i].Downloaded)
                {
                    item.IsPlayed = true; //alle episodes zijn gezien
                    Helpers.Logger.WriteSimpel(_Seasons[i].Season + " is al gezien");
                }
                if (_Seasons[i].Watched == 0) //0 items gezien
                {
                    if (_Seasons[i].Downloaded == 0) //geen episodes lokaal, en niets gezien.
                    {
                        item.IsRemote = true;
                        Helpers.Logger.WriteSimpel(_Seasons[i].Season + " geen episodes lokaal, en niets gezien.");
                    }
                }
                Helpers.Logger.WriteSimpel("Watched : " + _Seasons[i].Watched + "\n firstUnwachted: " + firstUnwatched.ToString());
                if (_Seasons[i].Watched < _Seasons[i].Downloaded && firstUnwatched == -1)
                {
                    firstUnwatched = i;
                }
                m_Facade.Add(item);
                //Helpers.Logger.WriteSimpel("Added item " + item.Label + " to facade");
                item = null;
            }

            //selecteer wat de user geselect had :-)
            try
            {
                m_Facade.SelectedListItemIndex = Selected_Season_Facade;
            }
            catch (Exception Ex)
            {
                Helpers.Logger.WriteSimpel("\t\tLoadSeasons() " + Ex.Message);
            }
            Helpers.Logger.WriteSimpel("firstUnwatched: " + firstUnwatched.ToString());
            m_Facade.SelectedListItemIndex = firstUnwatched;
            GUIControl.FocusControl(m_Facade.GetID, m_Facade.ListView.GetID);


        }

        void LoadEpisodes(int ShowID, int Season)
        {
            int firstUnwatched = -1;
            Helpers.Logger.WriteSimpel("LoadEpisodes()");           

            _Episodes = Database.DBEpisodes.getEpisodes(ShowID, Season);

            this.m_Facade.Clear();

            GUIListItem item;

            for (int i = 0; i < _Episodes.Count; i++)
            {
                item = new GUIListItem();
                item.ItemId = _Episodes[i].EpisodeID;
                item.Label = _Episodes[i].Season.ToString() + "x" + _Episodes[i].Episode.ToString() + " " + _Episodes[i].Titel;
                item.Label2 = _Episodes[i].AirDate;
                Helpers.Logger.WriteSimpel("Watched : " + _Episodes[i].Wachted.ToString() + "\n firstUnwachted: " + firstUnwatched.ToString());
                if (_Episodes[i].Wachted == 0 && firstUnwatched < 0)
                {
                    firstUnwatched = i;
                }
                
                
                //Condities om te bepalen welke kleur iets krijgt :-)
                if (_Episodes[i].Wachted == 1)
                {
                    item.IsPlayed = true; //alle episodes zijn gezien
                }
                m_Facade.Add(item);

                //Helpers.Logger.WriteSimpel("Added Episode " + _Episodes[i].FileName + " to the facade");
                item = null;
            }
            Helpers.Logger.WriteSimpel("firstUnwatched: " + firstUnwatched.ToString());
            m_Facade.SelectedListItemIndex = firstUnwatched;
            GUIControl.FocusControl(m_Facade.GetID, m_Facade.ListView.GetID);

        }

        void PlayEpisode()
        {
            Helpers.Logger.WriteSimpel(_Episodes[Selected_EpisodeID_Facade].FileName);
            if (!File.Exists(_Episodes[Selected_EpisodeID_Facade].FileName))
            {
                GeefMelding("Fout:", "Bestand bestaat lokaal niet meer!!");
                currentSelection = 2;
                decideListView();
                return;
            }

            Helpers.Logger.Write("Started videoplay : " + _Episodes[Selected_EpisodeID_Facade].FileName, "PlayEpisode()");
            m_VideoHandler.EpisodeID = _Episodes[Selected_EpisodeID_Facade].EpisodeID;
            m_VideoHandler.Play(_Episodes[Selected_EpisodeID_Facade].FileName);            
            m_VideoHandler.isPlaying = true;
        }
  

        //Try to load the billboard
        void Series_OnItemSelected(int selectedIndex)
        {
            //Helpers.Logger.WriteSimpel("Series_OnItemSelected()");         
     
            if (File.Exists(THUMBS_FOLDER + @"\" + _Shows[selectedIndex].ShowID + @".jpg"))
            {
                billboard_image = THUMBS_FOLDER + @"\" + _Shows[selectedIndex].ShowID + @".jpg";
            }
            else
            {
                billboard_image = THUMBS_FOLDER + @"\0.jpg";                
            }

            titel_serie = _Shows[selectedIndex].ShowName;

            m_BillBoard.SetFileName(billboard_image);
            m_ShowTitel.Label = titel_serie;
            m_Gekeken_Episodes.Label = "Gekeken afleveringen: " + _Shows[selectedIndex].Wachted;
            m_Aantal_Episodes.Label = "Aantal afleveringen: " + _Shows[selectedIndex].Downloaded;            
            m_ShowSummary.Label = _Shows[selectedIndex].Summary.Replace("<br />","");
            m_Score.Percentage = (Convert.ToInt32(Math.Round(Convert.ToDouble(_Shows[selectedIndex].Score))) +1) * 10;
            m_Volgende_Aflevering.Label = "Volgende aflevering: " + getDate(_Shows[selectedIndex].NextEpisode);
            m_Vorige_Aflevering.Label = "Vorige aflevering: " + getDate(_Shows[selectedIndex].LastAired);   
            m_Duratie.Label = "Duratie: " + _Shows[selectedIndex].Runtime.ToString() + " minuten.";
            m_ShowStatus.Label = "Status: " + _Shows[selectedIndex].ShowStatus;

            if (_Shows[selectedIndex].SubsNL == 0)
            {
                m_SubsNL.SetFileName(GUIGraphicsContext.Skin + @"\Media\nl_0.gif");
            }
            else
            {
                m_SubsNL.SetFileName(GUIGraphicsContext.Skin + @"\Media\nl_1.gif");
            }
            if (_Shows[selectedIndex].SubsEN == 0)
            {
                m_SubsEN.SetFileName(GUIGraphicsContext.Skin + @"\Media\usa_0.gif");
            }
            else
            {
                m_SubsEN.SetFileName(GUIGraphicsContext.Skin + @"\Media\usa_1.gif");
            }
            m_votes.Label = "";
//            fillGUIData();

        }

        void Season_OnItemSelected(int selectedIndex)
        {
            //Helpers.Logger.WriteSimpel("Season_OnItemSelected()");            

            m_Gekeken_Episodes.Label = "Gekeken afleveringen: " + _Seasons[selectedIndex].Watched.ToString();
            m_Aantal_Episodes.Label = "Aantal afleveringen: " + _Seasons[selectedIndex].Downloaded.ToString();            

            if (_Seasons[selectedIndex].SubsNL == 0)
            {
                m_SubsNL.SetFileName(GUIGraphicsContext.Skin + @"\Media\nl_0.gif");
            }
            else
            {
                m_SubsNL.SetFileName(GUIGraphicsContext.Skin + @"\Media\nl_1.gif");
            }
            if (_Seasons[selectedIndex].SubsEN == 0)
            {
                m_SubsEN.SetFileName(GUIGraphicsContext.Skin + @"\Media\usa_0.gif");
            }
            else
            {
                m_SubsEN.SetFileName(GUIGraphicsContext.Skin + @"\Media\usa_1.gif");
            }
            m_votes.Label = "";
            //Helpers.Logger.WriteSimpel("Another Season selected!");
        }

        private void Episode_OnItemSelected(int selectedIndex)
        {
            //Helpers.Logger.WriteSimpel("Episode_OnItemSelected() - selectedIndex: " + selectedIndex.ToString());
            if (_Episodes[selectedIndex].SubsNL == 0)
            {
                m_SubsNL.SetFileName(GUIGraphicsContext.Skin + @"\Media\nl_0.gif");
            }
            else
            {
                m_SubsNL.SetFileName(GUIGraphicsContext.Skin + @"\Media\nl_1.gif");
            }
            if (_Episodes[selectedIndex].SubsEN == 0)
            {
                m_SubsEN.SetFileName(GUIGraphicsContext.Skin + @"\Media\usa_0.gif");
            }
            else
            {
                m_SubsEN.SetFileName(GUIGraphicsContext.Skin + @"\Media\usa_1.gif");
            }
            m_Score.Percentage = (Convert.ToInt32(Math.Round(Convert.ToDouble(_Episodes[selectedIndex].Score))) + 1) * 10;
            m_votes.Label = "(" + _Episodes[selectedIndex].Stemmen + ") stemmen";

        }

        //private void fillGUIData()
        //{
    
            
        //}

        private string getDate(string source)
        {
            if (source == null)
            {
                return "";
            }
            if (source.Length == 0)
            {
                return "";
            }
            string _datum;

            source.Replace("januari", "01");
            source.Replace("februari", "02");
            source.Replace("maart", "03");
            source.Replace("april", "04");
            source.Replace("mei", "05");
            source.Replace("juni", "06");
            source.Replace("juli", "07");
            source.Replace("augustus", "08");
            source.Replace("september", "09");
            source.Replace("oktober", "10");
            source.Replace("november", "11");
            source.Replace("december", "12");

            //Helpers.Logger.WriteSimpel("Source: " + source);
            
            DateTime datum;

            Helpers.Logger.WriteSimpel("Source : " + source.ToString());

            datum = DateTime.Parse(source);

            string maand = "";

            switch (datum.Month)
            {
                case 1:
                    maand = "jan";
                    break;
                case 2:
                    maand = "feb";
                    break;
                case 3:
                    maand = "mrt";
                    break;
                case 4:
                    maand = "apr";
                    break;
                case 5:
                    maand = "mei";
                    break;
                case 6:
                    maand = "jun";
                    break;
                case 7:
                    maand = "jul";
                    break;
                case 8:
                    maand = "aug";
                    break;
                case 9:
                    maand = "sep";
                    break;
                case 10:
                    maand = "okt";
                    break;
                case 11:
                    maand = "nov";
                    break;
                case 12:
                    maand = "dec";
                    break;
            }

            _datum = datum.Day.ToString() + "-" + maand + "-" + datum.Year.ToString();
            if (datum.Year == 1970)
            {
                _datum = "(onbekend)";
            }
            Helpers.Logger.WriteSimpel("Datum:" + _datum);
            Helpers.Logger.WriteSimpel("stop getDate()");
            return _datum;

        }

        private void updateLocalSeries()
        {
            Helpers.Logger.WriteSimpel("Update local series vanaf MP GUI...");
            
            List<string> _ImportPaths;
            List<string> _ImportFolders;
            List<string> _ImportFiles;
            
            _ImportPaths = Database.Database.GetImportPaths();
            _ImportFolders = Import.FileSystemHelper.getScanFolders(_ImportPaths);
            

            for (int i = 0; i < _ImportFolders.Count; i++)
            {
                _ImportFiles = Import.FileSystemHelper.ListFiles(_ImportFolders[i]);
                foreach (string ImportFile in _ImportFiles)
                {
                    Import.EpisodeParser Episode = new Import.EpisodeParser();
                    Episode.ParseEpisode(ImportFile);
                }
            }
            API.BierdopjeEpisodes.WhichShowsNeedUpdate();
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET Downloaded = 0");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET Downloaded = 1 WHERE EpisodeID IN (SELECT * FROM LocalEpisodeIDs)");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET SubNLDownloaded = 1 WHERE EpisodeID IN (SELECT DISTINCT EpisodeID FROM LocalSubsID WHERE SubNL > 0)");
            Helpers.SqliteHelper.ExecuteQuery("UPDATE BierdopjeEpisodes SET SubENDownloaded = 1 WHERE EpisodeID IN (SELECT DISTINCT EpisodeID FROM LocalSubsID WHERE SubEN > 0)");
        }
    }
}